package com.ruoyi.system.service.impl;

import com.ruoyi.common.enums.RoleEnum;
import com.ruoyi.system.domain.dto.OpenApiDTO;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.fasterxml.jackson.databind.json.JsonMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.DefDrill;
import com.ruoyi.system.domain.DefGainReview;
import com.ruoyi.system.domain.DefScoreRule;
import com.ruoyi.system.domain.DefTeam;
import com.ruoyi.system.domain.DefTeamMember;
import com.ruoyi.system.domain.dto.UserWithDrillDTO;
import com.ruoyi.system.domain.request.CompanyRequest;
import com.ruoyi.system.domain.request.GainRequest;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.domain.vo.DefCompanyListVo;
import com.ruoyi.system.domain.vo.DefDrillGainVo;
import com.ruoyi.system.domain.vo.DefGainListVo;
import com.ruoyi.system.domain.vo.DefGainVo;
import com.ruoyi.system.domain.vo.DefTeamCount;
import com.ruoyi.system.domain.vo.DefTeamDetailVo;
import com.ruoyi.system.domain.vo.DefTeamGainVo;
import com.ruoyi.system.domain.vo.GainCountVo;
import com.ruoyi.system.domain.vo.GainGaredeVo;
import com.ruoyi.system.enums.GainStatusEnum;
import com.ruoyi.system.enums.GardeEnym;
import com.ruoyi.system.enums.OperateEnum;
import com.ruoyi.system.enums.ResultEnum;
import com.ruoyi.system.enums.ScoreRoleTypeEnum;
import com.ruoyi.common.enums.TeamTypeEnum;
import com.ruoyi.system.mapper.DefCompanyMapper;
import com.ruoyi.system.mapper.DefDrillMapper;
import com.ruoyi.system.mapper.DefGainReviewMapper;
import com.ruoyi.system.mapper.DefScoreRuleMapper;
import com.ruoyi.system.mapper.DefTeamMapper;
import com.ruoyi.system.mapper.DefTeamMemberMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.DefGainMapper;
import com.ruoyi.system.domain.DefGain;
import com.ruoyi.system.service.IDefGainService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

/**
 * 成果管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-11
 */
@Service
public class DefGainServiceImpl implements IDefGainService 
{
    private static final Logger log = LoggerFactory.getLogger(DefGainServiceImpl.class);
    @Autowired
    private DefGainMapper defGainMapper;

    @Autowired
    private DefGainReviewMapper defGainReviewMapper;

    @Autowired
    private DefDrillMapper defDrillMapper;

    @Autowired
    private DefScoreRuleMapper defScoreRuleMapper;

    @Autowired
    private DefCompanyMapper defCompanyMapper;

    @Autowired
    private DefTeamMemberMapper defTeamMemberMapper;

    @Autowired
    private DefTeamMapper defTeamMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 查询成果管理
     * 
     * @param id 成果管理主键
     * @return 成果管理
     */
    @Override
    public DefGain selectDefGainById(Long id)
    {
        return defGainMapper.selectDefGainById(id);
    }

    /**
     * 查询成果管理详情
     *
     * @param id 成果管理主键
     * @return 成果管理
     */
    @Override
    public DefGainVo detail(Long id)
    {
        DefGainVo gainVo = new DefGainVo();
        DefGain defGain = defGainMapper.selectDefGainById(id);
        BeanUtils.copyProperties(defGain, gainVo);
        if (!StringUtils.isEmpty(gainVo.getImage())) {
            gainVo.setImageList(Arrays.asList(gainVo.getImage().split(",")));
        }
        try {
            gainVo.setFileList(new JsonMapper().readValue(gainVo.getFiles(), List.class));
        } catch (Exception e) {
            log.error("文件列表解析异常", e);
        }
        DefGainReview review = new DefGainReview();
        review.setGainId(id);
        List<DefGainReview> list = defGainReviewMapper.selectDefGainReviewList(review);
        gainVo.setList(list);
        return gainVo;
    }

    /**
     * 查询成果管理列表
     * 
     * @param defGain 成果管理
     * @return 成果管理
     */
    @Override
    public List<DefGain> selectDefGainList(DefGain defGain)
    {
        return defGainMapper.selectDefGainList(defGain);
    }

    /**
     * 新增成果管理
     * 
     * @param defGain 成果管理
     * @return 结果
     */
    @Override
    public int insertDefGain(DefGain defGain)
    {
        defGain.setCreateTime(DateUtils.getNowDate());
        return defGainMapper.insertDefGain(defGain);
    }

    /**
     * 修改成果管理
     * 
     * @param defGain 成果管理
     * @return 结果
     */
    @Override
    public int updateDefGain(DefGain defGain)
    {
        return defGainMapper.updateDefGain(defGain);
    }

    /**
     * 批量删除成果管理
     * 
     * @param ids 需要删除的成果管理主键
     * @return 结果
     */
    @Override
    public int deleteDefGainByIds(Long[] ids)
    {
        return defGainMapper.deleteDefGainByIds(ids);
    }

    /**
     * 删除成果管理信息
     * 
     * @param id 成果管理主键
     * @return 结果
     */
    @Override
    public int deleteDefGainById(Long id)
    {
        return defGainMapper.deleteDefGainById(id);
    }


    /**
     * 根据用户ID、获取类型和演练ID获取得分
     *
     * @param gainType 获取类型
     * @param teamId 队伍ID
     * @return 计算评分是加分还是减分
     *
     * 此方法旨在根据不同的用户和演练信息，结合得分规则，返回该用户在某演练中的得分
     * 它首先根据获取类型查找得分规则，然后根据用户所在的团队类型（攻击或防守）和规则类型来决定得分
     */
    public Integer getScore(Integer gainType, Integer teamId) {
        // 初始得分，默认为1
        int score = 1;
        // 通过获取类型查找默认得分规则
        DefScoreRule rule = defScoreRuleMapper.selectDefScoreRuleById(Long.valueOf(gainType));
        // 如果找不到对应的得分规则，抛出异常
        if (rule == null) {
            throw new RuntimeException("成果类型不存在");
        }
        // 获取用户所在的团队信息
        DefTeam team = defTeamMapper.selectDefTeamByTeamId(teamId);
        // 根据团队类型和得分规则类型计算得分
        if (TeamTypeEnum.DEFENSE.getDescription().equals(team.getTeamType())) {
            // 防守方减分
            if (ScoreRoleTypeEnum.SCORE_TYPE_2.getCode().equals(rule.getRuleType())) {
                 score = -1;
            }
        } else {
            // 攻击方加分
            if (ScoreRoleTypeEnum.SCORE_TYPE_1.getCode().equals(rule.getRuleType())) {
                score = -1;
            }
        }
        // 返回计算后的得分
        return score;
    }

    /**
     * 提交成果
     *
     * 此方法负责将成果提交到数据库，并记录该操作
     * 它包括设置增益申请的创建时间，状态为“待审核”，以及操作类型为“提交”
     *
     * @param defGain 增益申请对象，包含申请的相关信息
     * @return 操作是否成功的布尔值，通过插入操作的影响行数来判断
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean submitGain(DefGain defGain) {
        log.info("用户提交成果申请");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        defGain.setCreateBy(String.valueOf(loginUser.getUserId()));
        defGain.setDirllId(Long.valueOf(loginUser.getDrillId()));
        defGain.setCreateTime(new Timestamp(System.currentTimeMillis()));
        if (!CollectionUtils.isEmpty(defGain.getImageList())) {
            defGain.setImage(String.join(",", defGain.getImageList()));
        }
        if (!CollectionUtils.isEmpty(defGain.getFileList())) {
            try {
                defGain.setFiles(new JsonMapper().writeValueAsString(defGain.getFileList()));
            } catch (Exception e) {
                log.error("文件列表解析异常", e);
            }
        }
        DefTeam team = getTeam(loginUser.getUserId(), loginUser.getDrillId());
        defGain.setTeamId(team.getTeamId());
        defGain.setScore(0);
        defGain.setStatus(GainStatusEnum.WAIT.getValue());
        defGainMapper.insertDefGain(defGain);
        DefGainReview gainReview = new DefGainReview();
        gainReview.setGainId(defGain.getId());
        gainReview.setStatus(GainStatusEnum.WAIT.getValue());
        gainReview.setCreateTime(new Timestamp(System.currentTimeMillis()));
        SysUser sysUser = sysUserMapper.selectUserById(loginUser.getUserId());
        gainReview.setCreateBy(sysUser.getNickName());
        gainReview.setOperate(OperateEnum.SUBMIT.getValue());
        return defGainReviewMapper.insertDefGainReview(gainReview) > 0;
    }


    public DefTeam getTeam(Long userId, Integer drillId) {
        DefTeamMember teamMember = new DefTeamMember();
        teamMember.setTeamUser(Math.toIntExact(userId));
        teamMember.setDrillId(drillId);
        List<DefTeamMember> members = defTeamMemberMapper.selectDefTeamMemberList(teamMember);
        if (CollectionUtils.isEmpty(members)) {
            throw new RuntimeException("用户未加入任何团队");
        }
        DefTeam defTeam = defTeamMapper.selectDefTeamByTeamId(members.get(0).getTeamId());
        if (defTeam == null) {
            throw new RuntimeException("队伍不存在或已删除");
        }
        return defTeam;
    }

    /**
     * 提交收益审核
     *
     * @param gainReview 待提交的收益审核信息
     * @return 返回提交是否成功，成功返回true，否则返回false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean gainReview(DefGainReview gainReview) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        DefGain defGain = defGainMapper.selectDefGainById(gainReview.getGainId());
        if (defGain == null) {
             throw new RuntimeException("未找到对应的成果");
        }
        SysUser sysUser = sysUserMapper.selectUserById(loginUser.getUserId());
        UserWithDrillDTO teamMember = new UserWithDrillDTO();
        teamMember.setDrillId(loginUser.getDrillId());
        teamMember.setUserId(Math.toIntExact(loginUser.getUserId()));
        teamMember.setRoleId(RoleEnum.JUDGE.getCode());
        List<UserWithDrillVO> list = defTeamMemberMapper.userWithDrill(teamMember);
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("用户不是裁判，无法审核");
        }
        gainReview.setCreateBy(sysUser.getNickName());
        gainReview.setCreateTime(new Timestamp(System.currentTimeMillis()));
        gainReview.setOperate(OperateEnum.REVIEW.getValue());

        Integer score = getScore(defGain.getGainType(), defGain.getTeamId());
        defGain.setScore(score * gainReview.getScore());
        Integer status = Objects.equals(gainReview.getResult(), ResultEnum.PASS.getValue()) ? GainStatusEnum.PASS.getValue() : GainStatusEnum.NOT_PASS.getValue();
        defGain.setStatus(status);
        if (Objects.equals(status, GainStatusEnum.NOT_PASS.getValue())) {
            defGain.setScore(0);
        }
        defGain.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        defGain.setUpdateBy(String.valueOf(loginUser.getUserId()));
        defGainMapper.updateDefGain(defGain);
        gainReview.setStatus(status);
        return defGainReviewMapper.insertDefGainReview(gainReview) > 0;
    }

    /**
     * 提交成果申诉
     *
     * @param gainReview 待提交的收益审核信息
     * @return 返回提交是否成功，成功返回true，否则返回false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean gainAppeal(DefGainReview gainReview) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        DefGain defGain = defGainMapper.selectDefGainById(gainReview.getGainId());
        if (defGain == null) {
            throw new RuntimeException("未找到对应的成果");
        }
        SysUser sysUser = sysUserMapper.selectUserById(loginUser.getUserId());
        UserWithDrillDTO teamMember = new UserWithDrillDTO();
        teamMember.setDrillId(loginUser.getDrillId());
        teamMember.setTeamId(defGain.getTeamId());
        teamMember.setRoleId(RoleEnum.TEAM_MEMBER.getCode());
        teamMember.setUserId(Math.toIntExact(loginUser.getUserId()));
        List<UserWithDrillVO> list = defTeamMemberMapper.userWithDrill(teamMember);
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("用户不是此队成员，不能提交申诉");
        }
        gainReview.setCreateBy(sysUser.getNickName());
        gainReview.setCreateTime(new Timestamp(System.currentTimeMillis()));
        gainReview.setOperate(OperateEnum.APPEAL.getValue());
        defGain.setStatus(GainStatusEnum.APPEAL.getValue());
        defGain.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        defGain.setUpdateBy(String.valueOf(loginUser.getUserId()));
        defGainMapper.updateDefGain(defGain);
        gainReview.setStatus(GainStatusEnum.APPEAL.getValue());
        return defGainReviewMapper.insertDefGainReview(gainReview) > 0;
    }

    /**
     * 提交成果申诉审核
     *
     * @param gainReview 待提交的收益审核信息
     * @return 返回提交是否成功，成功返回true，否则返回false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean gainAppealReview(DefGainReview gainReview) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        DefGain defGain = defGainMapper.selectDefGainById(gainReview.getGainId());
        if (defGain == null) {
            throw new RuntimeException("未找到对应的成果");
        }
        SysUser sysUser = sysUserMapper.selectUserById(loginUser.getUserId());
        UserWithDrillDTO teamMember = new UserWithDrillDTO();
        teamMember.setDrillId(loginUser.getDrillId());
        teamMember.setUserId(Math.toIntExact(loginUser.getUserId()));
        teamMember.setRoleId(RoleEnum.JUDGE.getCode());
        List<UserWithDrillVO> list = defTeamMemberMapper.userWithDrill(teamMember);
        if (CollectionUtils.isEmpty(list)) {
            throw new RuntimeException("用户不是裁判，无法审核");
        }
        gainReview.setCreateBy(sysUser.getNickName());
        gainReview.setCreateTime(new Timestamp(System.currentTimeMillis()));
        gainReview.setOperate(OperateEnum.APPEAL_REVIEW.getValue());
        defGain.setGrade(gainReview.getGarde());
        Integer score = getScore(defGain.getGainType(), defGain.getTeamId());
        defGain.setScore(score * gainReview.getScore());
        Integer status = Objects.equals(gainReview.getResult(), ResultEnum.PASS.getValue()) ? GainStatusEnum.PASS.getValue() : GainStatusEnum.NOT_PASS.getValue();
        defGain.setStatus(status);
        if (Objects.equals(status, GainStatusEnum.NOT_PASS.getValue())) {
            defGain.setScore(0);
        }
        defGain.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        defGain.setUpdateBy(String.valueOf(loginUser.getUserId()));
        defGainMapper.updateDefGain(defGain);
        gainReview.setStatus(status);
        return defGainReviewMapper.insertDefGainReview(gainReview) > 0;
    }

    @Override
    public List<DefGainListVo> pageList(GainRequest request) {
        DefDrill defDrill = defDrillMapper.selectDefDrillByDrillId(request.getDrillId());
        List<DefGainListVo> vos = defGainMapper.pageList(request);
        for (DefGainListVo gainScore : vos) {
            if (Objects.equals(gainScore.getTeamType(), TeamTypeEnum.DEFENSE.getDescription())) {
                // gainScore.setScore(defDrill.getInitScore() + gainScore.getScore());
            } else if (Objects.equals(gainScore.getTeamType(), TeamTypeEnum.ATTACK.getDescription())) {
                gainScore.setScore(-1 * gainScore.getScore());
            }
        }
        return vos;
    }

    /**
     * 计算成果统计数据
     *
     * @param request 请求对象，包含收益查询的参数
     * @return 返回一个GainCountVo对象，包含各种状态的收益数量和总数量
     */
    @Override
    public GainCountVo gainCount(GainRequest request) {
        GainCountVo countVo = new GainCountVo();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        request.setDrillId(loginUser.getDrillId());
        DefDrill defDrill = defDrillMapper.selectDefDrillByDrillId(loginUser.getDrillId());
        List<GainCountVo.GainCount> gainCounts = defGainMapper.statusCount(request);
        Map<Integer, Integer> map = gainCounts.stream().collect(Collectors.toMap(GainCountVo.GainCount::getStatus, GainCountVo.GainCount::getCount));
        countVo.setStatu1(map.getOrDefault(GainStatusEnum.WAIT.getValue(), 0));
        countVo.setStatu2(map.getOrDefault(GainStatusEnum.PASS.getValue(), 0));
        countVo.setStatu3(map.getOrDefault(GainStatusEnum.NOT_PASS.getValue(), 0));
        countVo.setStatu4(map.getOrDefault(GainStatusEnum.APPEAL.getValue(), 0));
        countVo.setTotal(countVo.getStatu1() + countVo.getStatu2() + countVo.getStatu3() + countVo.getStatu4());
        List<GainCountVo.GainScore> gainScores = defGainMapper.scoreSum(request);
        for (GainCountVo.GainScore gainScore : gainScores) {
            switch (gainScore.getTeamType()) {
                case "攻击队":
                    countVo.setAttack(gainScore.getScore());
                    break;
                case "防守队":
                    countVo.setDefend(defDrill.getInitScore() + gainScore.getScore());
                    break;
            }
        }
        if (countVo.getTotal() > 0) {
            countVo.setRate(BigDecimal.valueOf(countVo.getStatu2() * 100L).divide(BigDecimal.valueOf(countVo.getTotal()), 2, RoundingMode.HALF_UP).doubleValue());
        }
        return countVo;
    }


    /**
     * 计算演练收益
     * 该方法用于汇总攻击队和防守队的演练得分，并分别存储他们的得分和公司计数
     *
     * @return DefDrillGainVo 返回一个包含演练收益数据的对象
     */
    @Override
    public DefDrillGainVo drillGain() {
        DefDrillGainVo countVo = new DefDrillGainVo();
        GainRequest request = new GainRequest();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        request.setDrillId(loginUser.getDrillId());
        DefDrill defDrill = defDrillMapper.selectDefDrillByDrillId(loginUser.getDrillId());
        List<GainCountVo.GainScore> gainScores = defGainMapper.scoreSum(request);
        for (GainCountVo.GainScore gainScore : gainScores) {
            switch (gainScore.getTeamType()) {
                case "攻击队":
                    countVo.setAttack(gainScore.getScore());
                    countVo.setAttackList(defGainMapper.companyCount(0L, "攻击队"));
                    break;
                case "防守队":
                    countVo.setDefend(defDrill.getInitScore() + gainScore.getScore());
                    countVo.setDefendList(defGainMapper.companyCount(0L, "防守队"));
                    break;
            }
        }
        return countVo;
    }


    @Override
    public List<GainGaredeVo> gainGaredes() {
        List<GainGaredeVo> gainGaredeVos = new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<GainGaredeVo> garedeVos = defGainMapper.gradeCount(loginUser.getDrillId());
        Map<Integer, GainGaredeVo> map = garedeVos.stream().collect(Collectors.toMap(GainGaredeVo::getGrade, Function.identity()));
        for (GardeEnym value : GardeEnym.values()) {
            GainGaredeVo orDefault = map.getOrDefault(value.getValue(), new GainGaredeVo(value.getValue(), 0));
            gainGaredeVos.add(orDefault);
        }
        return gainGaredeVos;
    }

    @Override
    public List<DefTeamGainVo> teamCount(Integer orderBy) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<DefTeamGainVo> gainVos = defGainMapper.teamCount(loginUser.getDrillId(), loginUser.getUserId());
        if (orderBy == 1) {
            return gainVos
                    .stream().sorted((a,b) -> a.getScore() - b.getScore()).collect(Collectors.toList());
        } else {
            return gainVos
                    .stream().sorted((b,a) -> a.getScore() - b.getScore()).collect(Collectors.toList());
        }
    }

    @Override
    public TableDataInfo companyPage(CompanyRequest request) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        DefTeam defTeam = new DefTeam();
        defTeam.setDrillId(loginUser.getDrillId());
        String companyIds = defTeamMapper.selectDefTeamList(defTeam).stream().map(DefTeam::getTeamCompany).collect(Collectors.joining(","));
        if (StringUtils.isBlank(companyIds)) {
            TableDataInfo tableDataInfo = new TableDataInfo();
            tableDataInfo.setCode(HttpStatus.SUCCESS);
            return tableDataInfo;
        }
        // 获取所有公司id
        List<Integer> ids = Arrays.stream(companyIds.split(",")).map(Integer::valueOf).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            TableDataInfo tableDataInfo = new TableDataInfo();
            tableDataInfo.setCode(HttpStatus.SUCCESS);
            return tableDataInfo;
        }
        if (!ids.contains(0)) {
            // 0 : 获取所有公司名称
            request.setIds(ids);
        }
        request.setDrillId(loginUser.getDrillId());
        Page<Object> page = PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<DefCompanyListVo> list = defCompanyMapper.selectList(request);
        TableDataInfo dataInfo = new TableDataInfo(list, (int) page.getTotal());
        dataInfo.setCode(HttpStatus.SUCCESS);
        return dataInfo;
    }

    @Override
    public List<DefTeamCount> teamTypeCount(Integer drillId) {
        List<DefTeamCount> counts = defGainMapper.teamTypeCount(drillId);
        Map<String, DefTeamCount> map = counts.stream().collect(Collectors.toMap(DefTeamCount::getTeamType, Function.identity()));
        for (TeamTypeEnum value : TeamTypeEnum.values()) {
            DefTeamCount count = map.get(value.getDescription());
            if (count == null) {
                counts.add(new DefTeamCount(0,0,0,0,value.getDescription()));
            } else if (value.getDescription().equals(TeamTypeEnum.ATTACK.getDescription())){
                // 攻击队分数都是负分，需要转换
                count.setScore(-1 * count.getScore());
            }
        }
        return counts;
    }

    @Override
    public List<DefGainAggVO> sortAttack(Integer drillId) {
        Assert.notNull(drillId,"请传入drillId");
        List<DefGainAggVO> defGainAggVOS = defGainMapper.sortAttack(drillId);
        int i=1;
        for (DefGainAggVO defGainAggVO : defGainAggVOS) {
            defGainAggVO.setNum(i);
            i++;
        }
        return defGainAggVOS;
    }

    @Override
    public List<DefGainAggVO> sortDefend(Integer drillId) {
        Assert.notNull(drillId,"请传入drillId");
        List<DefGainAggVO> defGainAggVOS = defGainMapper.sortDefend(drillId);
        int i=1;
        for (DefGainAggVO defGainAggVO : defGainAggVOS) {
            defGainAggVO.setNum(i);
            i++;
        }
        return defGainAggVOS;
    }

    @Override
    public List<DefGainResultVO> resultShow(Integer drillId) {
        Assert.notNull(drillId,"请传入drillId");
        List<DefGainResultVO> defGainResultVOS = defGainMapper.resultShow(drillId);
        for (DefGainResultVO defGainResultVO : defGainResultVOS) {
            if (Objects.nonNull(defGainResultVO.getGrade())) {
                switch (defGainResultVO.getGrade()){
                    case 0:
                        defGainResultVO.setLevel("低危");
                    case 1:
                        defGainResultVO.setLevel("中危");
                    case 2:
                        defGainResultVO.setLevel("高危");
                    default:
                        defGainResultVO.setLevel("低危");
                }
            }
        }
        return defGainResultVOS;
    }

    @Override
    public List<CountVO> unitSort(Integer drillId) {
        Assert.notNull(drillId,"请传入drillId");
        List<CountVO> defGainAggVOS = defGainMapper.unitSort(drillId);
        // int i=1;
        // for (CountVO defGainAggVO : defGainAggVOS) {
        //     defGainAggVO.setCount(i);
        //     i++;
        // }
        return defGainAggVOS;
    }

    @Override
    public LevelVO resultLevel(Integer drillId) {
        Assert.notNull(drillId,"请传入drillId");
        return defGainMapper.resultLevel(drillId);
    }

    @Override
    public List<DefGain> gain(OpenApiDTO dto) {
        return defGainMapper.gain(dto);
    }

    /**
     * 根据演练ID和团队ID获取团队得分及排名
     * 此方法首先查询演练中所有团队的得分情况，然后遍历这些得分记录，找到指定团队ID的得分信息，并设置其排名
     * 如果找到指定团队ID，则返回该团队的得分信息；如果未找到，则返回null
     *
     * @return 返回包含团队得分和排名的信息的DefTeamGainVo对象，如果未找到则返回null
     */
    @Override
    public DefTeamDetailVo getTeamScore() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 初始化排名，从1开始计数
        int rank = 1;
        DefTeam team = getTeam(loginUser.getUserId(), loginUser.getDrillId());
        // 从数据库中获取特定演练下所有团队的得分情况
        List<DefTeamGainVo> counts = defGainMapper.teamCount(loginUser.getDrillId(), null).stream().sorted((b,a) -> a.getScore() - b.getScore()).collect(Collectors.toList());
        // 遍历所有团队的得分记录
        for (DefTeamGainVo count : counts) {
            // 检查当前遍历的团队是否是目标团队
            if (Objects.equals(count.getTeamId(), team.getTeamId())) {
                // 如果是目标团队，设置其排名为当前排名值
                count.setTotal(rank);
                DefTeamDetailVo detailVo = new DefTeamDetailVo();
                DefTeam defTeam = defTeamMapper.selectDefTeamByTeamId(team.getTeamId());
                BeanUtils.copyProperties(count, detailVo);
                detailVo.setTeamType(defTeam.getTeamType());
                // 返回目标团队的得分信息
                return detailVo;
            }
            // 如果不是目标团队，增加排名计数，继续遍历下一个团队
            rank ++;
        }
        // 如果遍历完所有团队后仍未找到目标团队，返回null
        return null;
    }
}
